package com.bdtop.dbl.ui.activities.me;

import java.util.ArrayList;
import java.util.List;

import org.litepal.crud.DataSupport;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.R;
import com.bdtop.dbl.model.Msg;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.MsgResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.ui.activities.device.DeviceAddTipActivity;
import com.bdtop.dbl.ui.activities.main.MainActivity;
import com.bdtop.dbl.ui.adapters.MsgListAdapter;
import com.bdtop.dbl.ui.view.TitleBar;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;

/**
 * @ClassName: MsgActivity
 * @Description: TODO
 * @author: liyongqiang
 * @date:2014-10-10
 */
public class MsgActivity extends BaseActivity {

	private TitleBar mTitleBar;
	private ListView listView;
	private MsgListAdapter adapter;
	private boolean fromPush;

	private final List<Msg> msgList = new ArrayList<Msg>();

	private static final int RECORD_COUNT = 10; // 记录 record_count 条数据
	
	private Button btnClearMessage;

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_msg);
		super.onCreate(savedInstanceState);

		if (Preferences.isFromPush(this)) {
			fromPush = true;
			Preferences.saveFromPush(this, false);
		}

		mMdn = getIntent().getStringExtra("d_mdn");

		initViews();
		loadData();
	}

	private String mMdn;

	public static final void launch(Context context) {
		Intent intent = new Intent(context, MsgActivity.class);
		context.startActivity(intent);
	}

	public static final void launch(Context context, String mdn) {
		Intent intent = new Intent(context, MsgActivity.class);
		intent.putExtra("d_mdn", mdn);
		context.startActivity(intent);
	}

	private void loadData() {
		ServerApiFactory.getApiImpl().getMsgs(Preferences.getLoginSign(this), mGetDeviceListCallback);
		setAndShowWaitingMessage(R.string.loading);

	}

	private RequestCallback mGetDeviceListCallback = new RequestCallback() {

		@Override public void onSuccess(String rawData, Object response) {
			MsgResponse msgResponse = (MsgResponse) response;
			String status = msgResponse.getStatus();
			if (Constants.REQUEST_SUCCESS.equals(status)) {
				if (msgResponse.getMessage() != null) {
					List<Msg> respList = msgResponse.getMessage();
					msgList.addAll(0, respList);

					for (int i = respList.size(); i > 0; i--) {
						Msg msg = respList.get(i - 1);
						msg.save();
					}

					if (msgList.size() - RECORD_COUNT > 0) {
						List<Msg> delList = DataSupport.order("time asc").limit(msgList.size() - RECORD_COUNT).find(Msg.class);
						for (int j = 0; j < delList.size(); j++) {
							long delId = delList.get(j).getId();
							DataSupport.delete(Msg.class, delId);
						}

						msgList.removeAll(delList);
					}

					if (!TextUtils.isEmpty(mMdn)) {
						List<Msg> otherMdnList = new ArrayList<Msg>();
						for (Msg msg : msgList) {
							if (!mMdn.equals(msg.getMdn())) {
								otherMdnList.add(msg);
							}
						}
						msgList.removeAll(otherMdnList);
					}

					btnClearMessage.setVisibility(msgList.size() > 0 ? View.VISIBLE:View.GONE);
					
					adapter.notifyDataSetChanged();
				}

			}
			clearAndHiddenWaitingMessage();
		}

		@Override public void onError(int statusCode, Throwable e, String rawData) {
			clearAndHiddenWaitingMessage();
			if (NetworkUtils.isNetConnect(getApplicationContext())) {
				showToast(R.string.oper_error);
			} else {
				showToast(R.string.net_error);
			}
		}
	};

	private void initViews() {

		mTitleBar = (TitleBar) findViewById(R.id.title_bar);
		mTitleBar.setTitle(R.string.msg_manage_title);
		mTitleBar.setBelongActivity(this);
		
		mTitleBar.setBackListener(new View.OnClickListener() {
			@Override public void onClick(View v) {
				MainActivity.launch(MsgActivity.this);
			}
		});
		
		
		btnClearMessage = new Button(MsgActivity.this);
		btnClearMessage.setText(R.string.clear_message);
		btnClearMessage.setBackgroundResource(R.drawable.selector_title_blue_btn_bg);
		btnClearMessage.setTextColor(Color.WHITE);
		btnClearMessage.setVisibility(View.GONE);
		btnClearMessage.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View view) {
				msgList.clear();
				adapter.notifyDataSetChanged();
				btnClearMessage.setVisibility(View.GONE);
				
				if (!TextUtils.isEmpty(mMdn)) {
					DataSupport.deleteAll(Msg.class, "mdn = ?" , mMdn);
				} else {
					DataSupport.deleteAll(Msg.class);	
				}
			}
		});
		mTitleBar.addMenu(btnClearMessage);
		

		listView = (ListView) findViewById(R.id.msg_list);
		adapter = new MsgListAdapter(this);

		msgList.clear();
		msgList.addAll(DataSupport.order("time desc").find(Msg.class));
		
		if (!TextUtils.isEmpty(mMdn)) {
			List<Msg> otherMdnList = new ArrayList<Msg>();
			for (Msg msg : msgList) {
				if (!mMdn.equals(msg.getMdn())) {
					otherMdnList.add(msg);
				}
			}
			msgList.removeAll(otherMdnList);
		}
		if(msgList.size() > 0) {
			btnClearMessage.setVisibility(View.VISIBLE);
		}
		adapter.setList(msgList);

		listView.setAdapter(adapter);
	}

	@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 是否触发按键为back键
//		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			if (fromPush) {
//				fromPush = false;
//				MainActivity.launch(this, 3);
//				finish();
//				return true;
//			} else {
//				return super.onKeyDown(keyCode, event);
//			}
//
//		} else {
//			// 如果不是back键正常响应
//			return super.onKeyDown(keyCode, event);
//		}
		
		//fix 顶端通知栏有消息时，下拉点击，进入消息列表，点左上角返回箭头（←），直接回到桌面
		if (fromPush) {
			fromPush = false;
			MainActivity.launch(this, 3);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
